package com.jrx.anytxn.reporting.job.xib.step;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.entity.BtBatchStatus;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtBtBatchStatusMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.reporting.config.AnyTxnBatchProperties;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.mapper.ext.ExtMEastVStzfxxbMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobExecutionListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * @comment: 受托支付信息Listener
 * @author: liuzb
 * @date: 2022/8/23
 */
@Service
public class EntrustmentReportingListener implements JobExecutionListener {

    private static Logger logger = LoggerFactory.getLogger(EntrustmentReportingListener.class);

    @Autowired
    private IOrganizationTableService organizationTableService;
    @Resource
    private ExtBtBatchStatusMapper extBtBatchStatusMapper;
    @Resource
    private ExtMEastVStzfxxbMapper extMEastVStzfxxbMapper;
    @Resource
    private AnyTxnBatchProperties anyTxnBatchProperties;

    @Override
    public void beforeJob(JobExecution jobExecution) {
        //支持重跑
        logger.info("任务执行前...");
        PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
        // 设置指定对账日期
        Date today = anyTxnBatchProperties.getFileConfig().getToday();
        if (Objects.nonNull(today)) {
            org.setToday(today);
        }
        BtBatchStatus statuses = extBtBatchStatusMapper.selectByStatusAndJobName(ReportingConstant.BATCH_SATTUS_2, ReportingConstant.CUTOVER_END, org.getTenantId(), org.getToday());
        if (statuses != null) {
            String todayStr = DateUtils.format(org.getToday(), DateUtils.DATE_PATTERN_ANOTHER);
            logger.info("清空指定日期（{}）的m_east_v_stzfxxb表数据", todayStr);
            extMEastVStzfxxbMapper.deleteByBusinessDate(todayStr);
            logger.info("表数据指定日期（{}）清理完成", todayStr);
        }
    }

    @Override
    public void afterJob(JobExecution jobExecution) {
        logger.info("任务执行结束");
    }
}
